package com.daidai.service.employee.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daidai.dao.EmployeeMapper;
import com.daidai.domain.Common;
import com.daidai.domain.Employee;
import com.daidai.service.employee.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Value("${isStartRedis}")
    String isStartRedis;
    @Override
    public Common login(Employee employee,HttpSession session) {
        // 前后端分离 为了方便 使用员工id转为key
        Employee newems = employeeMapper.getAllByIdAndName(employee.getEid(), employee.getName());


        if(ObjectUtil.isNull(newems)){
            return new Common(500,"id 与 姓名不一致",null);
        }
        if( newems.getPasswd().equals(employee.getPasswd())){
            if(newems.getStatus()==1){
                return Common.error(500,"您已登录,请勿再次登录");
            }
            HashMap<String, Object> map = new HashMap<>();
            newems.setStatus(1);
            newems.setCounterid(employee.getCounterid());
            try {
                Boolean updateEms = updateEms(newems);
            }
            catch (Exception e){
                return Common.error(500,"登录失败");
            }

            if(isUseRedis()){
                redisTemplate.opsForValue().set("Ems_"+newems.getEid(),newems,1, TimeUnit.DAYS);
            }
            else {
                session.getServletContext().setAttribute("Ems_"+newems.getEid(),newems);
            }

            map.put("key","Ems_"+newems.getEid());
            newems.setPasswd(null);
            map.put("ems",newems);
            return Common.success("登录成功",map);
        }
        return Common.error(500,"密码错误");
    }

    @Override
    public List<Employee> getAllEms() {
        return employeeMapper.getAllEmployees();
    }

    public  Boolean updateEms(Employee employee){


        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        Integer eid = employee.getEid();
        System.out.println(eid.equals(1111));

        wrapper.eq("eid",eid);
        int i=0;
        try {
            i = employeeMapper.update(employee, wrapper);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

        if(i==1){
            return true;
        }
        return false;
    }

    @Override
    public Common isLoginByToken(String token,HttpSession session) {
        Object o=null;
        if(isUseRedis()){
            o = redisTemplate.opsForValue().get(token);
        }else{
            o=session.getServletContext().getAttribute(token);
        }

        if(ObjectUtil.isNull(o)){
            return Common.error(500,"该用户不存在");
        }
        Employee employee= (Employee)o;
        Employee employee1 = employeeMapper.selectOne(new QueryWrapper<Employee>().eq("eid", employee.getEid()));
        if(employee1.getStatus()==1){
            return Common.success("查询成功",employee);
        }
        return Common.error(500,"出错");
    }

    @Override
    public Common getEmsById(int eid) {
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("eid",eid);
        Employee employee = employeeMapper.selectOne(wrapper);
        if(ObjectUtil.isNull(employee)){
            return Common.error(500,"该用户不存在");
        }
        employee.setPasswd(null);
        return Common.success("查询成功",employee);
    }

    @Override
    public List<Employee> getWorkingEmS() {
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("status",1);
        return employeeMapper.selectList(wrapper);
    }

    @Override
    public List<Employee> getNoWorkEmS() {
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0);
        return employeeMapper.selectList(wrapper);
    }

    @Override
    public Common logout(String token,HttpSession session) {
        Common ems = isLoginByToken(token,session);
        if(ems.getStatus()!=200){
            return Common.error(500,"用户未登录");
        }

        if(isUseRedis()){
            redisTemplate.delete(token);
        }else{
            session.getServletContext().removeAttribute(token);
        }

        Employee employee = (Employee) ems.getData();
        Common emsById = getEmsById(employee.getEid());
        Employee data = (Employee) emsById.getData();
        data.setStatus(0);
        Boolean updateEms = updateEms(data);

        if(updateEms){
            return Common.success("退出成功");
        }
        return Common.error(500,"退出失败");
    }

    @Override
    public Common addEms(Employee employee) {
        try{
            employeeMapper.insert(employee);
        }
        catch (Exception e){
            return Common.error(500,"添加失败");
        }
        return Common.success("添加成功");
    }

    @Override
    public Common delEms(int eid) {
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("eid",eid);
        try {
            int delete = employeeMapper.delete(wrapper);
            if(delete==1){
                return Common.success("删除成功");
            }
            return Common.error(500,"该用户不存在");
        }catch (Exception e){
            return Common.error(500,"删除失败");
        }
    }

    @Override
    public Boolean forceLeave(int eid,HttpSession session) {
        String token="Ems_"+eid;
        Common logout = logout(token, session);
        if(logout.getStatus()==200){
            return true;
        }
        return false;
    }
    public Boolean isUseRedis(){
        if(isStartRedis.equals("1")){
            return true;
        }
        return false;
    }
    public Common forceLogout(Employee employee,HttpSession session){
        Employee data= employeeMapper.selectOne(new QueryWrapper<Employee>().eq("eid", employee.getEid()));
        if(!ObjectUtil.isNull(data)){
            if(data.getPasswd().equals(employee.getPasswd())&&data.getName().equals(employee.getName())){
                Boolean aBoolean = forceLeave(employee.getEid(), session);
                if(aBoolean){
                    return Common.success("退出成功");
                }
                return Common.error(500,"退出失败");
            }
            return Common.error(500,"退出失败");
        }
        return Common.error(500,"退出失败");
    }
}
